package com.study.concurrent.C_ThreadSynchronizationHelperClass.b_ResourcesConcurrentContorl;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Created by 赵超 on 2017/3/25.
 * 文档打印队列
 */
public class PrintQueue {
    /**
     * 创建信号量对象
     */
    private final Semaphore semaphore;

    /**
     * 初始化信号量为二进制信号量 new Semaphore(1)（只有0、1两个计数状态）
     */
    public PrintQueue() {
        this.semaphore = new Semaphore(1);
    }

    /**
     * 文档打印工作
     * @param document
     */
    public void printJob(Object document) {
        try {
            // 获取信号量
            semaphore.acquire();
            long duration = (long) (Math.random() * 10);
            System.out.printf("%s 执行打印%s 打印周期 %d 秒\n",
                    Thread.currentThread().getName(), document.toString(), duration);
            TimeUnit.SECONDS.sleep(duration);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 关闭信号量
            semaphore.release();
        }
    }
}
